import QtQuick 2.15
import QtQuick.Window 2.15

Item {
    id: root
    
    // 属性接口
    property color penColor: "#DBBA92"
    property color brushColor: "#FFF8F0"
    property color textColor: "#DBBA92"
    property int borderRadius: 5
    property int textMargin: 8
    property string text: "你好！"
    property int fontSize: 15
    property bool fontBold: true
    property size triangleSize: Qt.size(10, 10)
    property int direction: 3  // 0=Left, 1=Right, 2=Top, 3=Bottom
    
    // 枚举（小写开头，符合QML命名规范）
    readonly property int directionLeft: 0
    readonly property int directionRight: 1
    readonly property int directionTop: 2
    readonly property int directionBottom: 3
    
    // 计算属性（延迟计算，避免初始化时出错）
    property rect bubbleRect: Qt.rect(0, 0, 100, 50)
    property rect textRect: Qt.rect(8, 8, 84, 34)  // 默认值，避免初始化时计算
    
    // 更新计算属性
    function updateRects() {
        bubbleRect = calculateBubbleRect()
        textRect = Qt.rect(
            bubbleRect.x + textMargin,
            bubbleRect.y + textMargin,
            Math.max(0, bubbleRect.width - 2 * textMargin),
            Math.max(0, bubbleRect.height - 2 * textMargin)
        )
        // 更新矩形后请求重绘
        if (bubbleCanvas) {
            bubbleCanvas.requestPaint()
        }
    }
    
    // 计算气泡主体矩形
    function calculateBubbleRect() {
        if (width <= 0 || height <= 0) {
            return Qt.rect(0, 0, 100, 50)  // 返回默认值
        }
        
        var triW = triangleSize.width || 10
        var triH = triangleSize.height || 10
        
        switch (direction) {
        case directionBottom:
            return Qt.rect(0, triH, width, Math.max(0, height - triH))
        case directionTop:
            return Qt.rect(0, 0, width, Math.max(0, height - triH))
        case directionRight:
            return Qt.rect(triW, 0, Math.max(0, width - triW), height)
        case directionLeft:
            return Qt.rect(0, 0, Math.max(0, width - triW), height)
        default:
            return Qt.rect(0, 0, width, height)
        }
    }
    
    // 计算三角形路径
    function calculateTrianglePath() {
        if (width <= 0 || height <= 0) {
            return []
        }
        
        try {
            var triW = (triangleSize && triangleSize.width) ? triangleSize.width : 10
            var triH = (triangleSize && triangleSize.height) ? triangleSize.height : 10
            var path = []
            
            switch (direction) {
            case directionBottom:
                path = [
                    Qt.point(width / 2, 0),
                    Qt.point(width / 2 + triW / 2, triH),
                    Qt.point(width / 2 - triW / 2, triH)
                ]
                break
            case directionTop:
                path = [
                    Qt.point(width / 2, height),
                    Qt.point(width / 2 + triW / 2, height - triH),
                    Qt.point(width / 2 - triW / 2, height - triH)
                ]
                break
            case directionRight:
                path = [
                    Qt.point(0, height / 2),
                    Qt.point(triW, height / 2 - triH / 2),
                    Qt.point(triW, height / 2 + triH / 2)
                ]
                break
            case directionLeft:
                path = [
                    Qt.point(width, height / 2),
                    Qt.point(width - triW, height / 2 - triH / 2),
                    Qt.point(width - triW, height / 2 + triH / 2)
                ]
                break
            default:
                return []
            }
            return path
        } catch (e) {
            return []
        }
    }
    
    // 计算最佳大小
    function calculateOptimalSize() {
        try {
            var fm = Qt.fontMetrics({
                pixelSize: fontSize || 15,
                bold: fontBold || false
            })
            
            var screenWidth = Screen.width || 800
            var maxTextWidth = Math.min(500, screenWidth / 3)
            var textRect = fm.boundingRect(
                Qt.rect(0, 0, maxTextWidth, 300),
                Qt.TextWordWrap | Qt.AlignCenter,
                text || ""
            )
            
            var contentWidth = Math.max(100, Math.min(500, textRect.width + 2 * (textMargin || 8)))
            var contentHeight = Math.max(50, Math.min(300, textRect.height + 2 * (textMargin || 8)))
            
            var triW = (triangleSize && triangleSize.width) ? triangleSize.width : 10
            var triH = (triangleSize && triangleSize.height) ? triangleSize.height : 10
            var totalSize
            
            switch (direction) {
            case directionTop:
            case directionBottom:
                totalSize = Qt.size(contentWidth, contentHeight + triH)
                break
            case directionLeft:
            case directionRight:
                totalSize = Qt.size(contentWidth + triW, contentHeight)
                break
            default:
                totalSize = Qt.size(contentWidth, contentHeight)
            }
            
            totalSize.height *= 1.2
            return totalSize
        } catch (e) {
            // 如果出错，返回默认大小
            return Qt.size(200, 100)
        }
    }
    
    // 更新大小
    function updateSize() {
        try {
            var optimalSize = calculateOptimalSize()
            if (optimalSize && optimalSize.width > 0 && optimalSize.height > 0) {
                root.width = optimalSize.width
                root.height = optimalSize.height
                updateRects()  // 更新矩形
            }
        } catch (e) {
            // 忽略错误，使用默认大小
            root.width = 200
            root.height = 100
            updateRects()
        }
    }
    
    Component.onCompleted: {
        // 延迟更新大小，确保父组件已初始化
        Qt.callLater(function() {
            updateSize()
            updateRects()
        })
    }
    
    onWidthChanged: updateRects()
    onHeightChanged: updateRects()
    
    onTextChanged: {
        Qt.callLater(function() {
            updateSize()
        })
    }
    onFontSizeChanged: {
        Qt.callLater(function() {
            updateSize()
        })
    }
    onTextMarginChanged: {
        Qt.callLater(function() {
            updateSize()
        })
    }
    onTriangleSizeChanged: {
        Qt.callLater(function() {
            updateSize()
        })
    }
    onDirectionChanged: {
        Qt.callLater(function() {
            updateSize()
        })
    }
    
    // 暴露Canvas供外部访问
    property alias canvas: bubbleCanvas
    
    // 绘制气泡
    Canvas {
        id: bubbleCanvas
        anchors.fill: parent
        
        onPaint: {
            try {
                if (width <= 0 || height <= 0) {
                    return
                }
                
                var ctx = getContext("2d")
                if (!ctx) {
                    return
                }
                
                ctx.clearRect(0, 0, width, height)
                
                var rect = bubbleRect
                if (!rect || rect.width <= 0 || rect.height <= 0) {
                    return
                }
                
                var triPath = calculateTrianglePath()
                
                ctx.save()
                ctx.beginPath()
                
                // 绘制圆角矩形主体
                var br = Math.max(0, Math.min(borderRadius || 5, rect.width / 2, rect.height / 2))
                ctx.moveTo(rect.x + br, rect.y)
                ctx.lineTo(rect.x + rect.width - br, rect.y)
                ctx.quadraticCurveTo(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + br)
                ctx.lineTo(rect.x + rect.width, rect.y + rect.height - br)
                ctx.quadraticCurveTo(rect.x + rect.width, rect.y + rect.height, rect.x + rect.width - br, rect.y + rect.height)
                ctx.lineTo(rect.x + br, rect.y + rect.height)
                ctx.quadraticCurveTo(rect.x, rect.y + rect.height, rect.x, rect.y + rect.height - br)
                ctx.lineTo(rect.x, rect.y + br)
                ctx.quadraticCurveTo(rect.x, rect.y, rect.x + br, rect.y)
                ctx.closePath()
                
                // 添加三角形
                if (triPath && triPath.length >= 3) {
                    ctx.moveTo(triPath[0].x, triPath[0].y)
                    ctx.lineTo(triPath[1].x, triPath[1].y)
                    ctx.lineTo(triPath[2].x, triPath[2].y)
                    ctx.closePath()
                }
                
                // 填充
                ctx.fillStyle = brushColor || "#FFF8F0"
                ctx.fill()
                
                // 描边
                ctx.strokeStyle = penColor || "#DBBA92"
                ctx.lineWidth = 2
                ctx.stroke()
                
                ctx.restore()
            } catch (e) {
                // 忽略绘制错误
            }
        }
        
        Component.onCompleted: {
            // 延迟绘制，确保组件完全初始化
            Qt.callLater(function() {
                if (width > 0 && height > 0) {
                    requestPaint()
                }
            })
        }
        
        onWidthChanged: {
            Qt.callLater(function() {
                if (width > 0 && height > 0) {
                    requestPaint()
                }
            })
        }
        
        onHeightChanged: {
            Qt.callLater(function() {
                if (width > 0 && height > 0) {
                    requestPaint()
                }
            })
        }
    }
    
    // 文本
    Text {
        id: bubbleText
        x: textRect.x
        y: textRect.y
        width: textRect.width
        height: textRect.height
        
        text: root.text
        font.pixelSize: root.fontSize
        font.bold: root.fontBold
        color: root.textColor
        wrapMode: Text.WordWrap
        horizontalAlignment: Text.AlignHCenter
        verticalAlignment: Text.AlignVCenter
        
        onTextChanged: bubbleCanvas.requestPaint()
        onWidthChanged: bubbleCanvas.requestPaint()
        onHeightChanged: bubbleCanvas.requestPaint()
    }
    
    onPenColorChanged: bubbleCanvas.requestPaint()
    onBrushColorChanged: bubbleCanvas.requestPaint()
    onBorderRadiusChanged: bubbleCanvas.requestPaint()
}

